package cn.tedu.com.ExceptionHandle;

import cn.tedu.com.bean.ResponseEntity;
import cn.tedu.com.enums.ReturnCode;
import cn.tedu.com.exception.BusinessException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
@Slf4j
public class GlogalExceptionHanle {

    @ExceptionHandler(value = BusinessException.class)
    public void handleBusiness(BusinessException be, HttpServletResponse response) throws IOException {
        log.error("业务错误信息==>{}",be);
        ResponseEntity responseEntity = new ResponseEntity(ReturnCode.BUSINESS_EXCEPTION);
        String json = JSON.toJSONString(responseEntity);
        PrintWriter writer = response.getWriter();
        writer.write(json);
        writer.flush();
        writer.close();
//        return responseEntity;
    }

    @ExceptionHandler(value = Exception.class)
    public void hanldException(Exception ex,HttpServletResponse response) throws IOException {
        log.error("Excetion===>{}",ex);
        ResponseEntity responseEntity = new ResponseEntity(ReturnCode.SERVER_EXCEPION);
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(responseEntity));
        writer.flush();
        writer.close();
//        return responseEntity;
    }
}
